package org.cqust.backend.service.mission;

import lombok.RequiredArgsConstructor;
import org.cqust.backend.exception.BusinessException;
import org.cqust.backend.dto.request.mission.StepCreateRequestDTO;
import org.cqust.backend.dto.request.mission.StepMiniRequestDTO;
import org.cqust.backend.dto.request.mission.StepUpdateRequestDTO;
import org.cqust.backend.dto.response.mission.StepVersionDTO;
import org.cqust.backend.entity.mission.MissionStepVersion;
import org.cqust.backend.entity.mission.MissionVersion;
import org.cqust.backend.repository.mission.MissionStepAttemptRepository;
import org.cqust.backend.repository.mission.MissionStepVersionRepository;
import org.cqust.backend.repository.mission.MissionVersionRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class MissionStepService {
    private final MissionVersionRepository missionVersionRepository;
    private final MissionStepVersionRepository missionStepVersionRepository;
    private final MissionStepAttemptRepository stepAttemptRepository;

    // 带版本控制的步骤更新
    // 需要stepDTO必须具有：id
    @Transactional
    public boolean updateStepWithVersionControl(StepUpdateRequestDTO stepDTO) {
        //获取当前版本的信息
        MissionStepVersion currentStepVersion = missionStepVersionRepository.findById(stepDTO.getId())
                .orElseThrow(() -> new BusinessException("未找到ID为 " + stepDTO.getId() + " 的任务步骤"));
        if (currentStepVersion.getObsolete()) {
            throw new BusinessException("不允许修改已弃用的数据");
        }
        //装填missionId
        stepDTO.setMissionId(currentStepVersion.getMissionId());

        //是否有学生已经做了这个步骤？
        boolean hasAttempts = stepAttemptRepository.existsByStepVersionId(stepDTO.getId());

        if (hasAttempts) {
            //包含记录，则归档旧版本，新增数据
            archiveOldStepVersions(currentStepVersion);
            createNewStepVersion(stepDTO);
        }
        else {
            //不包含记录，可以安全的修改数据库中的数据
            updateCurrentVersion(currentStepVersion, stepDTO);
        }

        return true;
    }
    
    private void updateCurrentVersion(MissionStepVersion step, StepUpdateRequestDTO dto) {
        missionStepVersionRepository.updateXml(dto.getConfigXml(),dto.getId());
        // step.setOrder(dto.getOrder());
        // // step.setConfigXml(dto.getConfigXml());
        // return missionStepVersionRepository.save(step);
        // step.setTitle(dto.getTitle());
        // step.setDescription(dto.getDescription());
        // step.setScore(dto.getScore());
        // step.setObsolete(false);
        // step.setMissionVersionId(step.getMissionVersionId());
        // step.setMissionId(dto.getMissionId());


    }

    //归档旧版本StepVersion
    private void archiveOldStepVersions(MissionStepVersion oldStep){
        // 获取当前最新的missionVersion
        MissionVersion currentMissionVersion = missionVersionRepository.findCurrentMissionVersionByMissionId(oldStep.getMissionId())
                .orElseThrow(() -> new BusinessException("未找到ID为 " + oldStep.getMissionId() + " 的活动任务"));

        //将当前版本的stepVersion，进行归档，让其指向目前最新的missionVersion
        missionStepVersionRepository.updateByStepVersionId_SetMissionVersionIdAndObsoleteTrue(
                oldStep.getId(), currentMissionVersion.getId());
    }

    // === 添加新版本的stepVersion ===
    private void createNewStepVersion(StepMiniRequestDTO dto) {
        MissionStepVersion newVersion = new MissionStepVersion();
        //确保id为null，实现新增数据而非修改原有数据
        newVersion.setId(null);
        newVersion.setMissionId(dto.getMissionId());
        newVersion.setTitle(dto.getTitle());
        newVersion.setDescription(dto.getDescription());
        newVersion.setScore(dto.getScore());
        newVersion.setOrder(dto.getOrder());
        newVersion.setObsolete(false);
        missionStepVersionRepository.save(newVersion);
    }

    public List<StepVersionDTO> getLatestStepsByMissionId(Long missionId) {
        List<MissionStepVersion> stepVersions = missionStepVersionRepository.findByMissionId(missionId, false);
        if(stepVersions.isEmpty()){
            if (missionVersionRepository.findCurrentMissionVersionByMissionId(missionId).isEmpty()) {
                throw new BusinessException("未找到Id为 " + missionId + " 的任务");
            }
        }
        return stepVersions.stream().map(StepVersionDTO::new).toList();
    }

    public boolean addStepToMission(StepCreateRequestDTO stepRequest) {
        createNewStepVersion(stepRequest);
        return true;
    }
}
